from PySide2.QtCore import  QRunnable,Signal,QObject,QProcess

import requests
import os
class downloadExe(QRunnable):
    def __init__(self,*args):
        super().__init__()
        self.Signals = preSignal()
        self.args = args
        #print(self.args)
        

    def downloadFile(self,url,dst,task_name):
        now_dlsize=0
        chunk_sizes=1024 
        with requests.get(url,stream=True) as req:#(5)
            self.Signals.task_name.emit(task_name)
            total_size = int(req.headers['content-length']) 
            with open(dst, 'ab') as f:
                for chunk in req.iter_content(chunk_size=chunk_sizes): #(6)
                    if chunk:
                        f.write(chunk)
                        now_dlsize += chunk_sizes
                        progressValue=int(now_dlsize/total_size *100)
                        self.Signals.progress.emit(progressValue)
            if task_name=="Setup.exe" :
                self.Signals.isSetup.emit(dst)
    def run(self):
        if self.args:
            for arg in self.args:
                URL=arg[0]
                DST=arg[1]
                task_name=arg[2]                
                if os.path.exists(DST):
                    os.remove(DST)
                    self.downloadFile(URL,DST,task_name) 
                   
                else:
                    self.downloadFile(URL,DST,task_name)

            self.Signals.stop.emit(True)
        else:
            pass



                    
                    

        
class preSignal(QObject):   

    progress = Signal(int)
    task_name =Signal(str)
    stop = Signal(bool)
    isSetup = Signal(str)
